package com.hisky.cms.menu.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hisky.cms.menu.service.MenuService;
import com.hisky.cms.menu.vo.Menu;

@Controller
@RequestMapping("menu")
public class MenuController {
	@Autowired
	MenuService menuService;

	@RequestMapping("list")
	public ModelAndView getList(Integer parrentId) {
		ModelAndView mav = new ModelAndView("menu/list");
		if (parrentId == null)
			parrentId = 0;
		Menu temp = new Menu();
		temp.setParrentId(parrentId);
		List<Menu> menus = menuService.getList(temp);
		mav.addObject("menus", menus);
		return mav;
	}

	@RequestMapping(value = "getChildren")
	@ResponseBody
	public List<Menu> getChildren(Integer parrentId) {
		try {
			if (parrentId == null)
				parrentId = 0;
			Menu temp = new Menu();
			temp.setParrentId(parrentId);
			List<Menu> menus = menuService.getList(temp);
			return menus;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@RequestMapping(value = "add", method = { RequestMethod.GET })
	public ModelAndView add(Integer parrentId) {
		ModelAndView mav = new ModelAndView("menu/add");
		mav.addObject("parrentId", parrentId);
		return mav;
	}

	@RequestMapping(value = "add", method = { RequestMethod.POST })
	@ResponseBody
	public int add(Menu menu) {
		try {
			menuService.add(menu);
			return menu.getMenuId();
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	@RequestMapping(value = "updateOrderNo")
	@ResponseBody
	public int updateOrderNo(Integer menuId, String type) {
		try {
			return menuService.updateOrderNo(menuId, type);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	@RequestMapping(value = "update", method = { RequestMethod.GET })
	public ModelAndView update(Integer menuId) {
		ModelAndView mav = new ModelAndView("menu/update");
		Menu menu = menuService.get(menuId);
		mav.addObject("menu", menu);
		return mav;
	}

	@RequestMapping(value = "update", method = { RequestMethod.POST })
	@ResponseBody
	public int update(Menu menu) {
		try {
			menuService.update(menu);
			return menu.getMenuId();
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	@RequestMapping(value = "delete")
	@ResponseBody
	public int delete(Integer menuId) {
		try {
			return menuService.delete(menuId);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

}
